package com.hjs.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 编写一个程序，开启三个线程，线程id分别为A，B，C，每个线程打印自己的id打印10遍
 * ABCABCABCABCABCABCABCABCABCABC
 *
 * @author hanjinsong
 * @date 2020-02-19 16:11
 */
public class TestABCAlternate {
    public static void main(String[] args) {
        AlternateDemo alternateDemo = new AlternateDemo();

        for (int i = 0; i < 10; i++) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    alternateDemo.PrintA();
                }
            }, "A").start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    alternateDemo.PrintB();
                }
            }, "B").start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    alternateDemo.PrintC();
                }
            }, "C").start();
        }
    }

}

class AlternateDemo{
    private int num = 1;

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void PrintA(){
        lock.lock();
        try {
            if (num  != 1) {
                condition1.await();
            }
            System.out.print(Thread.currentThread().getName());
            num = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void PrintB(){
        lock.lock();
        try {
            if (num  != 2) {
                condition2.await();
            }
            System.out.print(Thread.currentThread().getName());
            num = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void PrintC(){
        lock.lock();
        try {
            if (num  != 3) {
                condition3.await();
            }
            System.out.print(Thread.currentThread().getName());
            num = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
